//
//  DBComposeController.swift
//  大波微博swift
//
//  Created by 大波 on 16/3/6.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import SVProgressHUD

class DBComposeController: UIViewController {
    
    /// 微博文字长度
    let DBStatusTextLength = 25
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    
    func keyboardWillChange(notification: NSNotification) {
        
        let changeFrame = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        let duration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        
        let toolBarBottomCon = -(UIScreen.height - changeFrame.origin.y)
        
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(toolBarBottomCon)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // MARK: - 准备UI
    
    private func prepareUI() {
        
        setupNavigationBar()
        
        setupTextView()
        
        setPhotoSelector()
        
        setToolBar()
        
        setLengthTipView()
    }
    
    private func setupTextView() {
        
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view)
        }
    }
    
    private func setupNavigationBar() {
        
        setupTitleView()
        
        setNavigationBarButtom()
    }
    
    private func setNavigationBarButtom() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    private func setToolBar() {
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.height.equalTo(44)
            
            make.leading.trailing.bottom.equalTo(view)
        }
        
        toolBar.items = [UIBarButtonItem]()
        
        let itemSettings = [
            
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        for dic in itemSettings {
            
            let imageName = dic["imageName"]!
            
            let action = dic["action"]!
            
            let item = UIBarButtonItem(imageName: imageName)
            
            let button = item.customView as! UIButton
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            toolBar.items?.append(item)
            
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        toolBar.items?.removeLast()
    }
    
    private func setLengthTipView() {
        
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.text = String(DBStatusTextLength)
        
        lengthTipLabel.sizeToFit()
        
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(toolBar.snp_top).offset(-8)
            
            make.trailing.equalTo(view).offset(-8)
        }
    }
    
    
    private func setPhotoSelector() {
        
        // 把照片选择控制器添加到发布控制器的子控制器中
        addChildViewController(photoSelectorVC)
        
        // 获取照片选择控制器的collectionView
        let photoSelectorView = photoSelectorVC.collectionView!
        
        view.addSubview(photoSelectorView)
        
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            
            make.width.equalTo(UIScreen.width)
            
            make.height.equalTo(view).offset(UIScreen.height * 0.6)
            
            make.centerX.equalTo(view)
            
            make.top.equalTo(view).offset(UIScreen.height)
        }
    }
    
    
    // MARK: - 导航栏按钮点击事件
    
    @objc private func close() {
        
        textView.resignFirstResponder()
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func send() {
        
        let text = textView.emoticonText()
        
        let length = DBStatusTextLength - text.characters.count
        
        // 文字超过规定范围后提示用户处理
        if length < 0 {
            
            SVProgressHUD.showInfoWithStatus("发送微博不要超过25个字哟~!!!")
            
            return
        }

        SVProgressHUD.showWithStatus("正在发送微博", maskType: SVProgressHUDMaskType.Black)
        
        DBStatusesViewModel.sendStatuse(text, image: photoSelectorVC.photos.first) {
            
            (error) -> () in
            
            if error == nil {
                
                SVProgressHUD.showWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Black)
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    self.close()
                })
                
            } else {
                
                SVProgressHUD.showErrorWithStatus("发布微博失败", maskType: SVProgressHUDMaskType.Black)
                
                self.close()
                
                print("发布微博失败: \(error)")
            }
        }
    }
    
    
    private func setupTitleView() {
        
        let prefix = "发微博"
        
        if let name = DBUserAccountViewModel.shareUserAccountViewModel.userAccount?.screen_name {
            
            let titleLabel = UILabel()
            
            let title = prefix + "\n" + name
            
            titleLabel.text = title
            
            titleLabel.font = UIFont.systemFontOfSize(14)
            
            titleLabel.numberOfLines = 0
            
            titleLabel.textAlignment = NSTextAlignment.Center
            
            let attrString = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            
            attrString.setAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range)
            
            titleLabel.attributedText = attrString
            
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
            
        } else {
            
            navigationItem.title = prefix
        }
    }
    
    
    // MARK: - toolBarAction
    
    /// 图片点击事件
    @objc private func picture() {
        
        textView.resignFirstResponder()
    
        photoSelectorVC.collectionView!.snp_updateConstraints { (make) -> Void in
            
            make.top.equalTo(view).offset(UIScreen.height * 0.4)
        }
        
        UIView.animateWithDuration(0.3) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    /// #点击事件
    @objc private func trend() {
        
        print("trend")
    }
    
    /// @点击事件
    @objc private func mention() {
        
        print("mention")
    }
    
    /// 表情点击事件
    @objc private func emoticon(buttom: UIButton) {
        
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        if textView.inputView != nil {
            
            buttom.setImage(UIImage(named: "compose_keyboardbutton_background_highlighted"), forState: UIControlState.Highlighted)
            
            buttom.setImage(UIImage(named: "compose_keyboardbutton_background"), forState: UIControlState.Normal)
            
        } else {
            
            buttom.setImage(UIImage(named: "compose_emoticonbutton_background"), forState: UIControlState.Normal)
            
            buttom.setImage(UIImage(named: "compose_emoticonbutton_background_highlighted"), forState: UIControlState.Highlighted)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            
            self.textView.becomeFirstResponder()
        })
    }
    
    /// 加号点击事件
    @objc private func add() {
        
        print("add")
    }
    
    
    // MARK: - 懒加载
    
    /// 工具条
    private lazy var toolBar: UIToolbar = {
        
        let bar = UIToolbar()
        
        return bar
    }()
    
    /// textView
    private lazy var textView: DBTextView = {
        
        let text = DBTextView()
        
        // 设置弹簧效果
        text.alwaysBounceVertical = true
        
        // 退出键盘
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        text.placeholderString = "分享新鲜事..."
        
        text.font = UIFont.systemFontOfSize(14)
        
        text.delegate = self
        
        return text
    }()
    
    /// emoticonKeyboard
    private lazy var emoticonKeyboard: CZEmoticonKeyboard = {
        
        let kb = CZEmoticonKeyboard(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.width, height: 266)))
        
        kb.textView = self.textView
        
        return kb
    }()
    
    /// 文字长度label
    private lazy var lengthTipLabel: UILabel = UILabel(textColor: UIColor.lightGrayColor(), font: 12)
    
    private lazy var photoSelectorVC: DBPhotoSelectorController = DBPhotoSelectorController()
}

extension DBComposeController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        let length = textView.emoticonText().characters.count
        
        // 剩余长度
        let lastLength = DBStatusTextLength - length
        
        lengthTipLabel.text = String(lastLength)
        
        lengthTipLabel.textColor = lastLength > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
}
